package com.linxin.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */

/**
 * ControllerAdvice: 设置通知, 类上面有RestController和Controller的异常都会在这里捕获
 * ResponseBody: 返回json数据给前端
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法, 报注解后面的异常会在下面方法处理
     * 捕获账号重复的异常
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        // 输出异常日志
        log.error(exception.getMessage());

        // 判断用户名是否已存在
        if (exception.getMessage().contains("Duplicate")) {
            String[] split = exception.getMessage().split(" ");
            String account = split[2];
            return Result.error(account + "已存在");
        }

        return Result.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public Result<String> exceptionHandler(CustomException exception) {
        // 输出异常日志
        log.error(exception.getMessage());

        // 返回异常信息
        return Result.error(exception.getMessage());
    }
}
